<?php
/* 签到抽奖类 */
namespace Api\Controller;
use Think\Controller;
use Think\Log;
class PLotteryController extends Controller {

	protected $user = array();  //用户
 	
 	protected $start = '';
 	protected $end = '';
	public function __construct()
	{
		//解决跨域
		echoHeader();
		$phone = I('post.phone', '', 'trim');
        $this->user = session('p_user');
		if(!$this->user or $this->user['phone'] != $phone){
			return $this->ajaxReturn(array('err_code'=>10000, 'err_msg'=>'请先登录'));
		}
        $this->user = M("PUser")->where(array("phone"=>$phone, "is_deleted"=>0))->find();
		if (!$this->user) {
			return $this->ajaxReturn(array('err_code'=>10000, 'err_msg'=>'请先登录'));
		}
        $this->user['score']=user_score_sum($this->user['id']);
	}

    //签到首页
    public function index(){

        $lottery = $this->getLottery();
        if(!$lottery){
            $ret = array('err_code'=>10001, 'err_msg'=>'非抽奖时段，敬请期待。');
        }
		//获取对应转盘信息
		$prizeList = $this->getPrizeList($lottery['id']);
		if($prizeList){
			foreach ($prizeList as $k => $v) {
				unset($v['surplus']);
				$data[] = $v;
				if (count($data) >= 8) {
					break;
				}
			}
			$ret['err_code'] = 200;
			$ret['err_msg']  = $data;
            $ret['score']  = $lottery['score'];

        }else{
			$ret = array('err_code'=>10001, 'err_msg'=>'非抽奖时段，敬请期待');
		}		
		
		//$ret['start_time'] = $this->start;
		//$ret['end_time'] = $this->end;
		$this->ajaxReturn($ret, 'JSON');
	}


	 /**
     * 获取签到活动的奖品列表
     * @return mix       
     */
    public function getPrizeList($id)
    {
        //读取缓存

        $data['lottery_id'] = $id;
        $data['is_deleted'] = 0;
        $prize = M('PLotteryPrize')->field('id,name,url')
              ->where($data)->select();
        return $prize;
    }

    private function getLottery(){
        /*
    	$cacheKey = '__P_LOTTERY__';
        S(array('type'=>'redis'));
        if ($lottery = S($cacheKey)) {
            return $lottery;
        }
        */
    	$loMap['status'] = 1;
    	$loMap['is_deleted'] = 0;
    	$lottery = M("PLottery")->where($loMap)->order('id desc')->find();
        if (!$lottery) {
            return false;
        }else{
        //	S(array('type'=>'redis','expire'=>300));
        //	S($cacheKey, $lottery);
        	return $lottery;
        }
    }

    //抽奖
    public function doLottery()
    {
    	$lottery = $this->getLottery();
    	if (!$lottery) {
    		return $this->ajaxReturn(array("err_code"=>10001, "err_msg"=>'非抽奖时段，敬请期待。'));
    	}

    	if($this->user['lottery_time'] < 1 && $this->user['score'] < $lottery['score']){
    		return $this->ajaxReturn(array('err_code'=>10002, 'err_msg'=>'抽奖次数或积分不足，无法抽奖'));
    	}

        if($lottery['start_time'] > time()){
            return $this->ajaxReturn(array('err_code'=>10008, 'err_msg'=>'非抽奖时段，敬请期待'));
        }
        if($lottery['end_time'] < time()){
            return $this->ajaxReturn(array('err_code'=>10009, 'err_msg'=>'非抽奖时段，敬请期待'));
        }
    	$prizeMap['is_deleted'] = 0;
    	$prizeMap['lottery_id'] = $lottery['id'];
        $prizeList = M("PLotteryPrize")->where($prizeMap)->order('id asc')->select();
        if (!$prizeList) {
            return $this->ajaxReturn(array('err_code'=>10003, 'err_msg'=>'抽奖失败'));
        }

        $rand = rand(1, 10000);
        $prize = array();
        //Log::write(var_export($rand, true), 'rand');
        foreach ($prizeList as $v) {
            if($v['rand'] == 0){
                continue;
            }
            if($v['rand'] >= $rand){
                if($v['surplus'] > 0){
                    $prize = $v;
                }
                break;
            }else{
                $rand -= $v['rand'];
            }
        }
        if(empty($prize)){
            foreach ($prizeList as $v) {
                if($v['name'] == '谢谢参与'){
                    $prize = $v;
                    break;
                }
            }
        }

        if (empty($prize)) {
            $this->ajaxReturn(array('err_code'=>10004, 'err_msg'=>'抽奖失败'));
            return false;
        }
        //开启事务
        $model = M();
        $model->startTrans();

        //更新用户抽奖次数或积分
        $userMap['id'] = $this->user['id'];
        $userMap['is_deleted'] = 0;
        if ($this->user['lottery_time'] > 0) {
        	$updateRes = M("PUser")->where($userMap)->setDec('lottery_time', 1);
        }else if($this->user['score'] >= $lottery['score']){
            $updateRes=true;
        }else{
        	$updateRes = false;
        }

     	if (!$updateRes) {
     		$model->rollback();

            $this->ajaxReturn(array('err_code'=>10005, 'err_msg'=>'抽奖次数或积分不足，无法抽奖'));
     	}

        //插入抽奖记录
        $data['act_id'] = $lottery['id'];
        $data['user_id'] = $this->user['id'];
        $data['prize_id'] = $prize['id'];
        $data['prize_name'] = $prize['name'];
        $data['type'] = 4;  //1报名2导入3兑换4抽奖
        $data['is_deleted'] = 0;
        if($this->user['lottery_time'] > 0){
        	$data['score'] = 0;
        }else{
        	$data['score'] = -$lottery['score'];
            consume_score($this->user['id'],$lottery['score']);
        }
        $data['add_time'] = time();
        $insert = M('PScoreRecord')->add($data);

        if (!$insert) {
        	$model->rollback();
        	$this->ajaxReturn(array('err_code'=>10006, 'err_msg'=>'抽奖失败'));
        }


        $decSku = true;
        //更新奖品库存
        if ($prize['id'] and ($prize['name'] != '谢谢参与' or ($prize['name'] == '谢谢参与' and $prize['surplus'] > 0)) ) {
            $condition['id'] = $prize['id'];
            $condition['surplus'] = array('gt', 0);
            $decSku = M('PLotteryPrize')->where($condition)->setDec('surplus', 1);
        }
        if ($decSku) {
        	$model->commit();
        	unset($prize['add_time']);
        	unset($prize['lottery_id']);
        	unset($prize['sku']);
        	unset($prize['surplus']);
        	unset($prize['is_deleted']);
            unset($prize['rand']);
            $user = M("PUser")->where(array('id'=>$this->user['id']))->field('id,lottery_time')->find();
            $user['score']=user_score_sum($user['id']);
            return $this->ajaxReturn(array('err_code'=>200, 'err_msg'=>$prize, 'user'=>$user));
        }else{
            $model->rollback();
            return $this->ajaxReturn(array('err_code'=>10007, 'err_msg'=>'抽奖失败'));
        }
    }
}